import ffmpeg
import os
import logging
import subprocess
import random
import time
from datetime import datetime, timedelta
from config import config
from utils import setup_logger

logger = setup_logger()

class MetadataHandler:
    def __init__(self):
        pass

    def modify_video_metadata(self, video_path: str, output_path: str = None):
        """修改视频元数据，包括时间戳和编码参数"""
        if output_path is None:
            output_path = video_path

        try:
            # 1. 修改文件系统时间戳
            current_time = time.time()
            # 随机时间偏移（-7天 ~ +3天）
            time_offset = random.randint(-7 * 24 * 3600, 3 * 24 * 3600)

            os.utime(video_path, (current_time + time_offset, current_time + time_offset))
            logger.info(f"修改文件时间戳: {video_path}")

            # 2. 视频编码参数调整
            temp_path = video_path.replace('.mp4', '_temp.mp4')
            bitrate = random.randint(8000, 12000)  # 随机比特率（kbps）
            fps = random.uniform(23.976, 30.0)  # 随机帧率

            command = f'{config.ffmpeg_path} -i {video_path} -b:v {bitrate}k -r {fps} -y {temp_path}'
            subprocess.run(command, shell=True, check=True,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

            # 3. 伪造创建时间元数据
            creation_time = datetime.now() - timedelta(minutes=random.randint(10, 60))
            creation_time_str = creation_time.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'

            # 使用FFmpeg嵌入伪造的创建时间
            final_path = video_path.replace('.mp4', '_final.mp4')
            command = f'{config.ffmpeg_path} -i {temp_path} -metadata creation_time="{creation_time_str}" -codec copy -y {final_path}'
            subprocess.run(command, shell=True, check=True,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

            # 替换原始文件
            os.replace(final_path, output_path)
            if os.path.exists(temp_path):
                os.remove(temp_path)

            logger.info(f"元数据修改完成: {output_path}")
        except subprocess.CalledProcessError as e:
            logger.error(f"元数据修改失败: {e.stderr}")
            raise
        except Exception as e:
            logger.error(f"元数据修改失败: {str(e)}")
            raise

    def merge_video_audio(self, video_path: str, audio_path: str, output_path: str):
        """合并视频和音频文件"""
        try:
            command = f'{config.ffmpeg_path} -i {video_path} -i {audio_path} -c:v copy -c:a aac -strict experimental -y {output_path}'
            subprocess.run(command, shell=True, check=True,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            logger.info(f"视频音频合并完成: {output_path}")
        except subprocess.CalledProcessError as e:
            logger.error(f"合并失败: {e.stderr}")
            raise
        except Exception as e:
            logger.error(f"合并失败: {str(e)}")
            raise
